<template>
  <a-upload
    name="file"
    :max-count="1"
    :accept="props.accept"
    :file-list="fileUrl ? [fileUrl] : []"
    :before-upload="beforeUpload"
    @remove="handleRemove"
  >
    <a-button>
      <UploadOutlined />
      上传
    </a-button>
  </a-upload>
</template>

<script setup>
import { getCurrentInstance, ref, watch } from "vue";
import { UploadOutlined } from "@ant-design/icons-vue";
import _ from "lodash";

const { proxy } = getCurrentInstance();
const props = defineProps({ file: [Object, String], accept: String });
const fileUrl = ref(props.file);

const emit = defineEmits(["update:file"]);

const beforeUpload = (file) => {
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    proxy.$message.error("文件大小不能超过20MB!");
  }
  if (isLt20M) {
    fileUrl.value = file;
  }
  return false;
};

const handleRemove = () => {
  fileUrl.value = null;
};

watch(fileUrl, (v) => {
  emit("update:file", v);
});
</script>

<style lang="less" scoped></style>
